﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using System.Web.UI.WebControls;

namespace TimeManagementSystem
{
    public class Global : System.Web.HttpApplication
    {
        public static InputValidator inputValid = new InputValidator();

        protected void Application_Start(object sender, EventArgs e)
        {

        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {
            if (Request.Cookies["sessionId"] == null)
            {
                var aCookie = new HttpCookie("sessionId");
                aCookie.Value = "empty";
                aCookie.Expires = DateTime.Now.AddDays(1);
                Response.Cookies.Add(aCookie);
            }
            else if (Request.Cookies["sessionId"].Value.Length == 24 && !Request.Url.AbsolutePath.Contains("/Login.aspx"))
            {
                if (inputValid.GetUser(Request.Cookies["ASP.NET_SessionId"].Value, Request.Cookies["sessionId"].Value) == null)
                {
                    Setlogout();
                }
            }
            else if (Request.Cookies["sessionId"].Value.Length != 24 && Request.Cookies["sessionId"].Value != "empty" && !Request.Url.AbsolutePath.Contains(".aspx"))
            {
                Setlogout();
            }
            else if (Request.Url.AbsoluteUri.Contains("/Login.aspx") && Request.Cookies["sessionId"].Value.Length == 24)
            {
                if (inputValid.GetUser(Request.Cookies["ASP.NET_SessionId"].Value, Request.Cookies["sessionId"].Value) != null)
                {
                    Response.Redirect("/Default.aspx");
                }
            }
        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {
            if (!Request.Url.AbsoluteUri.Contains("/Login.aspx") && Request.Cookies["sessionId"].Value.Length!=24)
            {
                Response.Redirect("/Login.aspx");
            }
        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {

        }

        public void Setlogout()
        {
            Response.Cookies["sessionId"].Value = "empty";
            Response.Redirect("/Login.aspx");
        }
    }
}